import {messages} from "share/common";
/**
 * Created by Allen on 2018/1/25.
 */
import React from 'react'
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import { Button, Badge, message, Popconfirm } from 'antd'
import SlideFrame from 'components/slide-frame'
import NewRule from 'containers/expense-reimbursement-control/expense-standard/travel-policy/new-rule'
import travelPolicyService from 'containers/expense-reimbursement-control/expense-standard/travel-policy/travel-policy.service'
import ResizeTable from 'components/resize-table'

class TravelSubsidyDetail extends React.Component{
  constructor(props){
    super(props);

    this.state = {
      loading: false,
      showSlideFrame: false,
      data: [],
      nowRule: {},
      tab:"SUBSIDY",
      page: 0,
      pageSize: 10,
      pagination: {
        current: 0,
        total: 0
      },
      columns: [
        {title: messages('common.sequence'), dataIndex: 'index', width: '10%', key: 'index', render: (value, record, index) => index + 1 + this.state.pageSize * this.state.page},
        {title: messages('setting.key1199'/*城市级别*/), dataIndex: 'levelName', width: '10%', key: 'levelName',render:(value,record) => record.levelType === 0 ? <span>{messages('setting.key1037'/*通用*/)}</span> : record.levelType === 2 ? <span>{messages('setting.key1173'/*其他*/)}</span> : <span>{record.levelName}</span>},
        {title: messages('setting.key1187'/*适用人群*/), dataIndex: 'userGroupDTOs', width: '20%', key: 'userGroupDTOs', render: this.renderUserGroup},
        {title: messages('setting.key1181'/*币种*/), dataIndex: 'currency', width: '10%', key: 'currency', render: () => (<span>CNY</span>)},
        {title: messages('setting.key1203'/*金额*/), dataIndex: 'amount', width: '15%', key: 'amount'},
        {title: messages('common.column.status'), dataIndex: 'status', width: '10%', key: 'status', 'align': 'center',
          render: (value,record) => (
            <Badge status={value === 0 ? 'success' : 'error'}
                   text={value === 0 ? messages('common.enabled') : messages('common.disabled')}/>)
        }, //状态
        {title: messages('common.operation'), dataIndex: 'operation', "align":"center",
          render: (text, record) => (
            <span>
            <a href="#" onClick={(e) => this.handleEdit(e, record)}>{messages('common.edit')}</a>
            <span className="ant-divider"/>
            <a href="#" onClick={(e) => this.handleNewEdit(e, record)}>{messages('setting.key1188'/*复制并编辑*/)}</a>
            <span className="ant-divider"/>
            <Popconfirm onConfirm={(e) => this.handleDelete(e, record)} title={messages('setting.key1189'/*你确认要删除？*/)}>{/* 你确定要删除organizationName吗 */}
              <a href="#" onClick={(e) => {e.preventDefault();e.stopPropagation();}}>{messages('common.delete')}</a>
            </Popconfirm>
          </span>)
        },  //操作
      ],
      rulesList: menuRoute.getRouteItem('travel-policy','key'),
    }
  }

  componentWillMount(){
    const {typeId, type} = this.props.location.state;
    this.setState({
      typeId: typeId,
      type: type
    }, () => {
      this.getList(), this.getCityOptions()
    })
  }



  renderUserGroup = (record)=>{

    if(!record) return <span>{messages('setting.key1037'/*通用*/)}</span>
    if(record){
      if(record.length === 1){
        return record.map(item=>{
          return <span key={item.userGroupOID}>{item.name}</span>
        })
      }else{
        return record.map((item,index)=>{
          if(index === record.length-1){
            return <span key={item.userGroupOID}>{item.name}</span>
          }
          if(this.props.language.code === 'zh_cn'){
            return <span key={item.userGroupOID}>{item.name}，</span>
          }else{
            return <span key={item.userGroupOID}>{item.name},</span>
          }
        })
      }
    }
  }

  getList(){
    const {typeId, page, pageSize} = this.state;

    this.setState({loading: true});
    travelPolicyService.getSubsidyRuleList(typeId,page,pageSize).then((resp) => {
      this.setState({
        data: resp.data,
        loading: false,
        pagination: {
          current: this.state.page + 1,
          total: Number(resp.headers['x-total-count']),
          onChange: this.onChangePager
        }
      })
    }).catch((e) => {
      message.error(messages('common.operate.filed'));
      this.setState({loading: false})
    })
  }

  //获取城市级别
  getCityOptions = () => {
    travelPolicyService.getCityLevels().then((resp) => {
      resp.data.unshift(
        {levelName: '通用',id: '000000000'},
        {levelName: '其他',id: '111111111'});
      this.setState({cityOptions: resp.data});
    })
  };

  //点击分页
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
        loading: true
      }, () => {
        this.getList()
      })
  };

  //新建
  handleNew = () => {
    const { typeId } = this.state;
    this.setState({
      showSlideFrame: true,
      isNew: true,
      nowRule: {
        showSlideFrame: true,
        isNew: true,
        type: 'subsidy',
        typeId: typeId}})
  };

  //编辑
  handleEdit = (e,record) => {
    const { typeId } = this.state;
    this.setState({
      showSlideFrame: true,
      isNew: false,
      nowRule: {
        showSlideFrame: true,
        isNew: false,
        type: 'subsidy',
        typeId: typeId,
        record: record}})
  };

  //复制并编辑
  handleNewEdit = (e,record) => {
    const { typeId } = this.state;
    this.setState({
      showSlideFrame: true,
      isNew: true,
      nowRule: {
        showSlideFrame: true,
        isNew: true,
        type: 'subsidy',
        typeId: typeId,
        record: record}})
  };

  //删除
  handleDelete = (e,record) => {

    this.setState({loading: true});
    travelPolicyService.deleteTravelSubsidyRule(record.travelStandardOID).then((resp) => {
      if (resp.status === 200){
        this.setState({loading: false});
        message.success(messages('setting.key213'/*删除成功*/));
        this.getList();
      }
    }).catch(() => {
      this.setState({loading: false});
      message.error(messages('common.operate.filed'));
    })
  };

  handleCloseSlide = (success) => {
    success && this.getList();
    let nowRule = this.state.nowRule;
    nowRule.showSlideFrame = false;
    this.setState({
      showSlideFrame : false,
      nowRule: nowRule,
    })
  };

  goBack = ()=>{
    this.context.router.push(this.state.rulesList.url+`?tab=${this.state.tab}`)
  }

  render(){
    const { loading, data, pagination, columns, isNew, showSlideFrame ,nowRule, type } = this.state;

    return (
      <div>
        <div className="header-title">{messages('setting.key1204'/*差补设置*/)}</div>
        <div className="table-header">
          <div>{messages('setting.key1205'/*费用类型*/)}：{type}</div>
          <div className="table-header-title">{messages('common.total', {total:pagination.total})}</div>
          <div className="table-header-buttons">
            <Button type="primary" onClick={this.handleNew}>{messages('setting.key1191'/*新增规则*/)}</Button>{/*新建*/}
          </div>
        </div>

        <ResizeTable
          columns={columns}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          rowKey={record => record.id}
          bordered
          size="middle"
        />
        <SlideFrame content={NewRule}
                    title={isNew ? messages('setting.key1191'/*新增规则*/) : messages('setting.key1192'/*编辑规则*/)}
                    show={showSlideFrame}
                    onClose={()=>this.setState({showSlideFrame:false})}
                    afterClose={this.handleCloseSlide} params={nowRule}/>
        <div style={{textAlign:'right',marginTop:'20px'}}>
          <Button onClick={this.goBack}>{messages('common.back')}</Button>
        </div>
      </div>
    )
  }
}

TravelSubsidyDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return{
    language: state.main.language
  }
}

export default connect(mapStateToProps)(TravelSubsidyDetail);

